/*
 * @lc app=leetcode.cn id=166 lang=typescript
 *
 * [166] 分数到小数
 */

// @lc code=start
function fractionToDecimal(numerator: number, denominator: number): string {
  // 可以整除
  if (numerator % denominator === 0) {
    return String(numerator / denominator);
  }

  const ans: string[] = [];
  // 结果是否为负数
  // 分子和分母有一个为负数
  if (Number(numerator < 0) ^ Number(denominator < 0)) {
    ans.push('-');
  }

  numerator = Math.abs(numerator);
  denominator = Math.abs(denominator);
  // 整数部分
  const integerPart = Math.floor(numerator / denominator);
  ans.push(String(integerPart));
  ans.push('.');
  // 小数部分
  const fractionPart: string[] = [];
  const remaindIndex = new Map();
  let remaind = numerator % denominator;
  let index = 0;
  while (remaind !== 0 && !remaindIndex.has(remaind)) {
    remaindIndex.set(remaind, index++);
    remaind = remaind * 10;
    fractionPart.push(String(Math.floor(remaind / denominator)));
    remaind = remaind % denominator;
  }
  // 出现循环,需要给循环部分加上小括号
  if (remaind > 0) {
    const index = remaindIndex.get(remaind);
    fractionPart.splice(index, 0, '(');
    fractionPart.push(')');
  }

  ans.push(...fractionPart);

  return ans.join('');
}
// @lc code=end
